package com.gouwudai.gobbs.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;

import com.gouwudai.gobbs.common.IPageList;
import com.gouwudai.gobbs.dao.IUserGradeDAO;
import com.gouwudai.gobbs.pojo.TbbsGrade;
import com.litt.core.common.Utility;
import com.litt.core.exception.BusiException;
import com.litt.core.exception.DBException;

public class UserGradeDAOImpl extends BaseDAOImpl implements IUserGradeDAO 
{
	private static final Logger logger = Logger.getLogger(UserGradeDAOImpl.class);	
	private static final String BUSI_NAME = "用户等级信息";
	
	public void save(TbbsGrade tbbsGrade) throws BusiException
	{
    	if(this.loadByName(tbbsGrade.getGradeName())!=null)
    		throw new DBException("该用户等级名称已存在！");	
		super.saveObject(tbbsGrade);		
	}
	
	public TbbsGrade load(Integer id)
	{
		return (TbbsGrade)super.loadObject(TbbsGrade.class, id);
	} 
	
	/**
	 * 根据用户名获得用户信息
	 * @param gradeName
	 * @return
	 */
	public TbbsGrade loadByName(String gradeName)
	{		
		String hql = "from TbbsGrade where gradeName='"+gradeName+"'";	
		TbbsGrade masterGradeInfo = (TbbsGrade)super.uniqueResultHql(hql);
		
		return masterGradeInfo;
	}	
    
    public void update(TbbsGrade tbbsGrade) throws BusiException
    {
    	//验证    	
    	String vhql = "from TbbsGrade where gradeName='"+tbbsGrade.getGradeName()+"' and gradeId<>"+tbbsGrade.getGradeId();	
    	TbbsGrade masterGradeInfo = (TbbsGrade)super.uniqueResultHql(vhql);
		if(masterGradeInfo!=null)
			throw new DBException("该用户等级名称已存在！");	
		//验证结束
    	StringBuilder hql = new StringBuilder();
        hql.append("update TbbsGrade set gradeName=?"); 
        hql.append(", remark=?");
        hql.append(" where gradeId=?");
        super.updateObject(hql.toString(), new Object[]{
        	tbbsGrade.getGradeName(),
        	tbbsGrade.getRemark(),
        	tbbsGrade.getGradeId()});

    }
    
    public void delete(Integer gradeId) throws BusiException
    {
        //1.验证该等级下是否还有用户存在
    	String hql = "select count(*) from TbbsUserInfo where isdelFlag=0 and gradeId="+gradeId;
    	
    	int count = super.listHqlCount(hql);
    	if(count>0)
    		throw new BusiException("该等级下还有用户存在，不能删除");
    	//1.结束-----
    	super.deleteObject(TbbsGrade.class.getName(),"gradeId",gradeId);
    }
    
    public List listAll()
    { 
    	return super.listAll(TbbsGrade.class);
    }
    

    public IPageList listPage(int pageIndex,int pageSize,String sort)
    {       
    	StringBuilder listSql = new StringBuilder("SELECT * FROM TbbsGrade ");
        if(!Utility.isEmpty(sort))
            listSql.append(sort); 	
    	return super.listSqlPage(listSql.toString(),pageIndex,pageSize);
    }
    
}
